package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.entity.ShareFile;
import com.example.entity.TransferStation;
import com.example.mapper.ShareFileMapper;
import com.example.mapper.TransferStationMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 文件中转站业务处理
 **/
@Service
public class TransferStationService {

    @Resource
    private TransferStationMapper transferStationMapper;

    @Resource
    private ShareFileMapper shareFileMapper;

    /**
     * 新增
     */
    public void add(TransferStation transferStation) {
        transferStationMapper.insert(transferStation);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        transferStationMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            transferStationMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(TransferStation transferStation) {
        transferStationMapper.updateById(transferStation);
    }

    /**
     * 根据ID查询
     */
    public TransferStation selectById(Integer id) {
        return transferStationMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<TransferStation> selectAll(TransferStation transferStation) {
        return transferStationMapper.selectAll(transferStation);
    }

    /**
     * 分页查询
     */
    public PageInfo<TransferStation> selectPage(TransferStation transferStation, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<TransferStation> list = this.selectAll(transferStation);
        return PageInfo.of(list);
    }

    public TransferStation selectAndUserId(Integer id) {
        return transferStationMapper.selectByUserId(id);
    }

    @Transactional
    public void clearTransferStation(TransferStation transferStation) {
        TransferStation transferStation1 = transferStationMapper.selectById(transferStation.getId());
        if (ObjectUtil.isNotEmpty(transferStation1)) {
//            删除所有发送到该中转站的文件
            List<ShareFile> list = shareFileMapper.selectByTransferStationId(transferStation1.getId());
            for (ShareFile shareFile : list) {
                shareFileMapper.deleteById(shareFile.getId());
            }
//            更新中转站
            transferStation1.setCurrentSize(new BigDecimal(0));
            transferStationMapper.updateById(transferStation1);
        }
    }
}